require "singularity/oauth/client/version"
require 'oauth2'
require 'rails'
require "#{__dir__}/api"


Slient = Singularity::Oauth::Client
# 将api设置别名方便访问c
Slient::API = Singularity::Oauth::API

module Singularity
  module Oauth
    module Client
      # 设置属性 ##################################

      #服务器地址
      mattr_accessor :server_host
      @@server_host = 'http://localhost:4000/'

      #access_key
      mattr_accessor :access_key
      @@access_key = '3ae0b097be2e8078f5bab92a124da06a2447811f988c211a338586cceb8b0bcb'

      #secret_key
      mattr_accessor :secret_key
      @@secret_key = '472188dd79e4f5ab6a2ad91e52460f75b7e6e5215661e734698076a184f160e8'

      #授权域
      mattr_accessor :scopes
      @@scopes = 'public'

      #登陆之后用户信息回调接口
      mattr_accessor :user_info_callback_block
      @@user_info_callback_block = Proc.new do |user|
        p user
      end

      # 资源对象的名字
      mattr_accessor :resource
      @@resource = 'User'

      # 客户端认证程序的单例
      mattr_accessor :api
      @@api = nil

      # 公共token获取方法
      mattr_accessor :get_token
      @@get_token = nil

      # 公共token设置方法
      mattr_accessor :set_token
      @@set_token = nil
      #############################################

      # 加载生成器
      Dir.glob("#{__dir__}/generators/*_generator.rb").each { |file|
        require file
      }

      # 设置配置项
      def self.setup
        yield self

        @@api = Singularity::Oauth::API.new self.client_new, @@get_token, @@set_token
      end

      # 设置用户信息回调
      def self.user_info_callback(&block)
        @@user_info_callback_block = block
      end

      def self.client_new
        OAuth2::Client.new(@@access_key, @@secret_key, :site => @@server_host, parse: :json, raise_errors: false)
      end
    end
  end
end

module OAuth2
  class Error < StandardError
    attr_reader :response, :code, :description

    # standard error values include:
    # :invalid_request, :invalid_client, :invalid_token, :invalid_grant, :unsupported_grant_type, :invalid_scope
    def initialize(response)
      response.error = self
      @response = response

      message = []

      if response.parsed.is_a?(Hash)
        @code = response.parsed['error']
        @description = response.parsed['error_description']
        message << "#{@code}: #{@description}"
      end

      message << response.body.force_encoding("UTF-8")

      super(message.join("\n"))
    end
  end
end
